import { GAME_TYPE_ENUM } from "../base/EnumIndex";
import { Tools } from "../common/Tools";
import { NetworkManager } from "../manager/NetworkManager";
import { AdBase } from "./AdBase";
import { AdManager } from "./AdManager";
const wx = window['wx'];

export class AdManager_WX extends AdBase {
    static get ins() {
        return super.getInstance<AdManager_WX>();
    }
    gameName: string = "剧情大湿";
    /** (自己)appID */
    app_id: string = "wx8271ac7d9b48debf";
    /** bannerID */
    ad_banner_id: string = "adunit-64d55f82495fec1d";
    /** 插屏ID */
    ad_inter_id: string = "adunit-3e889a9a21c90ec2";
    /** (自己)激励ID */
    ad_video_id: string = "adunit-8af266d496e72ead";

    /**脑洞天花板微信版本暂时不开启广告 */
    isPlayAds = false;

    /**临时登录凭证 有效期3min */
    code: string = null;
    clickID: string = null;
    /**当前游戏id */
    gameId: number = 0;
    /**游戏类型（1微信 2抖音） */
    queryGameType: number = 2;

    /**用户openId */
    openId: string = null;

    /** 微信免费广告次数 */
    private freeAdNum: number = 0;

    /**免费解锁次数 */
    private freeUnlockNum: number = 0;
    /**免费提示次数 */
    private freeTipNum: number = 0;

    /** 加载或者初始化所有广告 */
    loadAllAd() {
        this.sysInfo = wx.getSystemInfoSync();
        // this.initBanner();
        this.initVideoAd();
        this.initFreeAds();
        this.initFreeUnlockNum();
        this.initFreeTipNum();
        this.addShareMenu();
    };
    /** 初始化加载 视频广告 */
    private initVideoAd() {
        let self = this;

        switch (this.gameType) {
            case GAME_TYPE_ENUM.Zui_Qiang_Zhe_Mo:
                this.ad_video_id = "adunit-21495f87fce4c3b6";
                this.gameName = "最强折磨";
                this.gameId = 9;
                this.queryGameType = 1;
                break;
            case GAME_TYPE_ENUM.NAO_LI_YONG_ZHE:
                this.ad_video_id = "adunit-95ef71f66d1af521";
                this.gameName = "脑力勇者";
                this.gameId = 12;
                this.queryGameType = 1;
                break;
            case GAME_TYPE_ENUM.WEN_ZI_WO_FU_LE:
                this.ad_video_id = "";
                this.gameName = "老六我服了";
                this.gameId = 0;
                this.queryGameType = 0;
                break;
            case GAME_TYPE_ENUM.WO_YAO_BIAN_TU_LE:
                this.ad_video_id = "adunit-cedce2f5233ef734";
                this.gameName = "我要变秃了";
                this.gameId = 7;
                this.queryGameType = 1;
                break;
        }
        AdManager.gameId = this.gameId;
        AdManager.queryGameType = this.queryGameType;
        this.initFreeAds();

        wx.login({
            success(res) {
                if (res.code) {
                    //发起网络请求
                    self.code = res.code;
                    if (self.gameId != 0) {
                        NetworkManager.getOpenId(self.gameId, self.queryGameType, self.code, (openId) => {
                            self.openId = openId;
                            NetworkManager.reportGameTime(self.gameId, openId, 1, self.clickID, self.queryGameType, null, null);
                        });
                    }
                } else {
                    console.log('登录失败！' + res.errMsg)
                }
            }
        })

        /**监听小游戏隐藏到后台的事件。锁屏、按 HOME 键退到桌面等操作会触发此事件。 */
        if (this.gameId != 0) {
            wx.onHide(() => {
                NetworkManager.reportGameTime(self.gameId, self.openId, 2, self.clickID, self.queryGameType, null, null);
            });
            wx.onShow(() => {
                NetworkManager.reportGameTime(self.gameId, self.openId, 1, self.clickID, self.queryGameType, null, null);
            })
        }

        this.ad_video = wx.createRewardedVideoAd({ adUnitId: self.ad_video_id })
        this.ad_video.load().then(() => {
            console.log("视频广告加载完成!");
        }).catch((err: any) => {
            console.log("视频load失败:", JSON.stringify(err))
        });
        this.ad_video.onError((err: any) => {
            this.errorVideo();
            console.log("视频出错:", JSON.stringify(err));
            // // 再手动加载一次
            // this.ad_video.load().then(() => {
            //     console.log("手动加载成功");
            //     this.ad_video.show();  // 加载成功后需要再显示广告
            // });
        });
        this.ad_video.onClose((res: any) => {
            // 用户点击了【关闭广告】按钮
            // 小于 2.1.0 的基础库版本，res 是一个 undefined
            if (res && res.isEnded || res === undefined) {
                console.log("正常播放结束，可以下发游戏奖励");
                this.finishVideo();
            } else {
                console.log("播放中途退出，不下发游戏奖励");
                this.showModal("未观看完视频", "观看完视频才能获得奖励哦", () => {
                    this.showVideoAd(this.videoBack, this.errorBack)
                }, () => {
                    this.errorVideo();
                });
            }
        });
    };
    /** 初始化加载 banner */
    private initBanner() {
        let self = this;
        let bannerAd = wx.createBannerAd({
            adUnitId: self.ad_banner_id,
            style: { left: 0, top: 0, width: 720 }
        })
        bannerAd.onResize((res: any) => {
            let w = this.sysInfo.screenWidth / 2;
            let h = this.sysInfo.screenHeight;
            bannerAd.style.left = w - bannerAd.style.realWidth / 2 + 0.1;
            bannerAd.style.top = h - bannerAd.style.realHeight + 0.1;
            bannerAd.style.width = this.sysInfo.screenWidth * 0.8;
            console.log("bannerAd加载成功");
        })
        bannerAd.onError((err: any) => {
            console.log(err)
        });
        this.ad_banner = bannerAd;
    };
    /** 显示Banner广告 */
    public showBanner() {
        if (!this.ad_banner) {
            this.initBanner();
        }
        this.ad_banner.show();
        console.log("showBanner");
    };
    /** 隐藏Banner广告 */
    public hideBanner() {
        if (!this.ad_banner) { return; }
        this.ad_banner.hide();
    };
    /** 播放插屏广告 */
    public showIntersAd() {
        // 定义插屏广告
        let interstitialAd = null;
        let self = this;
        interstitialAd = wx.createInterstitialAd({
            adUnitId: self.ad_inter_id
        });
        interstitialAd.show().catch((err: any) => {
            console.error(JSON.stringify(err))
        });
        console.log("showIntersAd");
    }
    /** 播放视频广告  成功回调   失败回调 */
    public showVideoAd(finishBack?: Function, errorBack?: Function, countNum?: number, freeType: number = -1) {
        // wx.showToast({
        //     title: '暂无视频广告！',
        //     icon: 'none',
        //     duration: 1500//持续的时间
        // })
        // return;
        this.videoBack = null;
        this.errorBack = null;
        if (finishBack) {
            this.videoBack = finishBack;
        } if (errorBack) {
            this.errorBack = errorBack;
        }

        if (this.freeAdNum > 0) {
            this.addFreeAds(-1);
            if (this.videoBack) {
                this.videoBack();
            }
            return;
        }

        if (freeType === 1) { //解锁关卡
            if (this.freeUnlockNum > 0) {
                this.addFreeUnlockNum(-1);
                if (this.videoBack) {
                    this.videoBack();
                }
                return;
            }
        }

        if (freeType === 2) { //关卡提示
            if (this.freeTipNum > 0) {
                this.addFreeTipNum(-1);
                if (this.videoBack) {
                    this.videoBack();
                }
                return;
            }
        }

        if (!this.isPlayAds && this.gameType == GAME_TYPE_ENUM.WEN_ZI_WO_FU_LE) {
            if (this.videoBack) {
                this.videoBack();
            }
            return;
        }

        if (!this.ad_video) {
            this.initVideoAd();
        }

        this.ad_video.show().then(() => {
            console.log("广告显示成功");
        }).catch((err: any) => {
            this.errorVideo();
            console.log("广告组件出现问题", JSON.stringify(err));
            // 再手动加载一次
            this.ad_video.load().then(() => {
                console.log("手动加载成功");
                this.ad_video.show();  // 加载成功后需要再显示广告
            });
        });
        console.log("showVideoAd");
    }
    /** 视频播放完成 */
    finishVideo() {
        if (this.videoBack) {
            this.videoBack();
        }
        this.videoBack = null;
        this.errorBack = null;
    }
    /** 视频播放失败 isOut 是否中途退出*/
    errorVideo() {
        if (this.errorBack) {
            this.errorBack();
        }
        this.videoBack = null;
        this.errorBack = null;
    };
    /** 分享视频   shareTitle 分享内容  imgUrl 分享图路径 resource下的 */
    shareFriends(shareTitle?: string, imgUrl: string = "share") {
        // wx.showShareMenu();
        wx.shareAppMessage({
            title: this.gameName,
            success(res: any) {
                console.log("分享成功:", res);
            },
            fail(res: any) {
                // 转发失败
                wx.showToast({
                    title: '分享失败',
                    icon: 'none',
                    duration: 1500//持续的时间
                })
            }
        });
    };
    /** 添加右上角三个点分享 */
    addShareMenu(shareTitle?: string, imgUrl: string = "share") {
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline'],
        });
    };
    /** 跳转其他更多游戏 */
    toMoreGame() {
        wx.navigateToMiniProgram({
            appId: 'wxda02fde13d108205',  //其他游戏的appid
            path: 'page/index/index?id=123',
            extraData: {
                foo: 'bar'
            },
            envVersion: 'develop',
            success(res: any) {

            }
        });
    };

    /** 复访相关初始化 */
    private initFreeAds() {
        this.freeAdNum = Tools.getStorage("freeAdNum");
        if (this.freeAdNum === null) {
            this.freeAdNum = 0;
        }
        // console.log("复访", this.fuFangFinished, this.freeAdNum)
    }

    /**签到 */
    public sign(num) {
        this.freeAdNum = Tools.getStorage("freeAdNum");
        this.addFreeAds(num);
    }

    /**签到2 */
    public sign2(num: any[]) {
        let type = num[0];
        if (type == 1) {//解锁关卡
            this.freeUnlockNum = Tools.getStorage("freeUnlockNum");
            this.addFreeUnlockNum(num[1]);
        } else if (type == 2) {//提示
            this.freeTipNum = Tools.getStorage("freeTipNum");
            this.addFreeTipNum(num[1]);
        } else {
            this.freeAdNum = Tools.getStorage("freeAdNum");
            this.addFreeAds(num[1]);
        }
    }

    /**初始化解锁次数 */
    private initFreeUnlockNum() {
        this.freeUnlockNum = Tools.getStorage("freeUnlockNum");
        if (this.freeUnlockNum === null) {
            this.freeUnlockNum = 0;
        }
    }

    /**初始化提示次数 */
    private initFreeTipNum() {
        this.freeTipNum = Tools.getStorage("freeTipNum");
        if (this.freeTipNum === null) {
            this.freeTipNum = 0;
        }

    }

    /** 添加免解锁次数 */
    private addFreeUnlockNum(num: number) {
        this.freeUnlockNum += num;
        Tools.setStorage("freeUnlockNum", this.freeUnlockNum);
    }

    /** 添加免提示次数 */
    private addFreeTipNum(num: number) {
        this.freeTipNum += num;
        Tools.setStorage("freeTipNum", this.freeTipNum);
    }

    /** 添加免视频广告次数 */
    private addFreeAds(num: number) {
        this.freeAdNum += num;
        Tools.setStorage("freeAdNum", this.freeAdNum);
        // console.log("addFreeAds", this.freeAdNum)
    }

    /** 震动 */
    vibrate(num: number) {
        if (num >= 15) {
            wx.vibrateLong({
                success(res: any) { console.log(res) },
                fail(res: any) { console.log(`vibrateLong调用失败:` + res); },
            });
        } else {
            wx.vibrateShort({
                success(res: any) { console.log(res) },
                fail(res: any) { console.log(`vibrateShort调用失败:` + res); },
            });
        }
    }
    /** 添加桌面功能 */
    addTable() {

    }
    /** 是否已经添加过桌面了 */
    isAddTable() {

    }
    /** 弹框  确定或者取消 */
    showModal(titleStr: string, infoStr: string, finishBack?: any, cancelBack?: any) {
        wx.showModal({
            title: titleStr,
            content: infoStr,
            success(res: any) {
                if (res.confirm) {
                    if (!finishBack) { return; }
                    finishBack();
                    console.log("showModal, 确定");
                } else if (res.cancel) {
                    if (!cancelBack) { return; }
                    cancelBack();
                    console.log("showModal, 取消");
                }
            },
            fail(res: any) {
                console.log(`showModal调用失败` + res);
            },
        });
    }
}